<?php
namespace App\Frontend;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;
use Phalcon\Loader;
use Phalcon\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{
	/**
	 * Register a specific autoloader for the module
	 */
	public function registerAutoloaders(DiInterface $dependencyInjector = null) {
// 		$loader = new Loader();
		
// 		$loader->registerNamespaces(array( 
// 			'App\Frontend\Controllers' => '../app/frontend/controllers/', 
// 			'App\Frontend\Models' => '../app/frontend/models/' 
// 		));
		
// 		$loader->register();
	}
	
	/**
	 * Register specific services for the module
	 */
	public function registerServices(DiInterface $di) {
			// Registering a dispatcher
		$di->set('dispatcher', function () {
			$dispatcher = new Dispatcher();
			$dispatcher->setDefaultNamespace("App\Frontend\Controllers");
			// 方法不存在跳转到404
			$evManager = new \Phalcon\Events\Manager();
			$evManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
			
				if ($exception->getCode() == Dispatcher::EXCEPTION_ACTION_NOT_FOUND) {
					// $dispatcher->forward(array(
					// 		'namespace' => 'App\Frontend\Controllers',
					// 		'controller' => 'http',
					// 		'action' => 'show404'
					// ));
					return false;
				}
			});
			$dispatcher->setEventsManager($evManager);
			return $dispatcher;
		});
		// 模板引擎编译目录配置
		$di->set('voltService', function ($view, $di) {
			$volt = new Volt($view, $di);
			
			$volt->setOptions(array(
				'compileAlways' => true,
				"compiledPath" => function ($templatePath) {
					$dirName = str_replace("../application/apps/", "", $templatePath);
					$dirName = str_replace("views/", "", $dirName);
					$compiledPath = "data/volt/default/";
					$dirNamePath = dirname($dirName);
					if (!is_dir($compiledPath . $dirNamePath)) {
						mkdir($compiledPath . $dirNamePath, 0777, true);
					}
					return $compiledPath . $dirName . '.php';
				}
			));
			return $volt;
		});
		
		// Registering the view component
		$di->set('view', function () {
			$view = new View();
			$view->setViewsDir('../Application/' . APPS_DIR . '/Frontend/Views/');
			$view->registerEngines([
				".phtml" => 'voltService'
			]);
			return $view;
		});
	}
}